<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="/js/vue.js"></script>
    <script src="/js/axios.min.js"></script>
    <script src="/element-ui/lib/index.js"></script>
    <link rel="stylesheet" href="/element-ui/lib/theme-chalk/index.css">
</head>
<body>
<div id="app">
    <el-button type="primary" @click="openDialog()">添加角色</el-button>
    <el-button type="danger" @click="del()">删除角色</el-button>
    <el-table
            :data="roles"
            border
            style="width: 100%"
            @selection-change="handleSelectionChange">
        <el-table-column
                type="selection"
                width="55">
        </el-table-column>
        <el-table-column
                fixed
                prop="roleName"
                label="角色名"
                width="150">
        </el-table-column>
        <el-table-column
                prop="remark"
                label="描述"
                width="120">
        </el-table-column>
        <el-table-column
                label="操作"
                width="300">
            <template slot-scope="scope">
                <div v-if="scope.row.rid!='5'">
                    <el-button @click="del(scope.row.rid)" type="text" size="small">删除</el-button>
                    <el-button type="text" size="small" @click="openDialog(scope.row)">编辑</el-button>
                    <el-button type="text" size="small" @click="openPermissionDialog(scope.row.rid)">分配权限</el-button>
                </div>
                <div v-else>
                    超级管理员拥有一切权限
                </div>

            </template>
        </el-table-column>
    </el-table>
    <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
    </el-pagination>
    <!--添加/修改角色的弹框-->
    <el-dialog title="角色管理" :visible.sync="dialogFormVisible">
        <el-form :model="role">
            <el-form-item label="角色名称" :label-width="formLabelWidth">
                <el-input v-model="role.roleName" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" :label-width="formLabelWidth">
                <el-input v-model="role.remark" autocomplete="off"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="saveRole">确 定</el-button>
        </div>
    </el-dialog>
    <!--权限树的弹框-->
    <el-dialog title="分配权限" :visible.sync="dialogPermissionVisible">
        <el-tree
                :data="ps"
                ref="tree"
                show-checkbox
                default-expand-all
                node-key="id"
                :default-checked-keys="checkedPermissionids"
                :props="defaultProps">
        </el-tree>

        <div style="text-align: right">
            <el-button type="primary" @click="saveRolePermission">确定</el-button>
        </div>
    </el-dialog>
</div>

<script>
    new Vue({
        el: "#app",
        data: {
            checkedPermissionids:[],//选中的权限
            dialogPermissionVisible:false,
            ps:[],//所有的权限
            defaultProps: {//后台响应的字段名和elementui中需要的属性名对应起来
                children: 'children',
                label: 'pname'
            },
            role:{//修改/添加的角色对象
                rid:undefined,
                roleName:undefined,
                remark:undefined,
            },
            dialogFormVisible: false,
            formLabelWidth: '120px',
            roles:[],
            pageNum:1,
            pageSize:5,
            total:undefined,
            checkedRids:[],//选中的角色的id
            targetRoleId:undefined  //点击当前行的角色id
        },
        methods: {
            saveRolePermission(){//重新分配权限
               let checkIds=this.$refs.tree.getCheckedKeys();
               let halfCheckedId=this.$refs.tree.getHalfCheckedKeys();
               halfCheckedId.forEach(item=>{
                   checkIds.push(item)
               });

               // console.log(checkIds)
                axios.put(`/permission/editRolePermission?roleId=${this.targetRoleId}&permissionIds=${checkIds.join(",")}`)
                .then(resp=>{
                    let data=resp.data;
                    if (data.code==200){
                        this.$message({
                            type:"success",
                            message:"分配成功"
                        });
                        this.dialogPermissionVisible=false;
                    }
                })
            },
            openPermissionDialog(roleId){//显示权限树
                this.targetRoleId=roleId;
                this.dialogPermissionVisible=true;
                //获取所有的权限
                axios.get("/permission").then(resp=>{
                    let data=resp.data;
                    this.ps=data.result;
                })
                //根据角色id查询原始权限
                axios.get(`/permission/getPermissionIdsByRoleId?roleId=${roleId}`).then(resp=>{
                    let data=resp.data;
                    this.checkedPermissionids=data.result
                })
            },
            del(rid){//确定删除
                if (rid){//单个删除
                    this.checkedRids=[];
                   this.checkedRids.push(rid);
                }

                if (this.checkedRids.length==0){
                    this.$message({
                        type:"warning",
                        message:"至少选中一条数据"
                    });
                    return;
                }


                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {//点击确定
                    axios.delete(`/role?ids=${this.checkedRids.join(",")}`).then(resp=>{
                        let data=resp.data;
                        if (data.code==200){
                            this.$message({
                                type:"success",
                                message:"删除成功"
                            });
                            this.initData();
                        }else{
                            this.$message({
                                type:"error",
                                message:data.msg
                            });
                        }
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });



            },
            handleSelectionChange(val) {//表格左侧复选框的点击事件
               // console.log(val)
                this.checkedRids=[];
                val.forEach(item=>{
                   this.checkedRids.push(item.rid)
                });
            },
            openDialog(item){//修改/添加弹框显示
                this.dialogFormVisible=true
                if (item){//修改
                    this.role={...item}
                }else{//添加
                    this.role={//修改/添加的角色对象
                        rid:undefined,
                        roleName:undefined,
                        remark:undefined,
                    }
                }
            },
            saveRole(){
                axios({
                    method:this.role.rid?"put":"post",
                    url:"/role",
                    data:this.role
                }).then(resp=>{
                    let data=resp.data;
                    if (data.code==200){
                        this.$message({
                            type:"success",
                            message:"操作成功"
                        });
                        this.dialogFormVisible=false;
                        this.initData();//刷新表格数据
                    }else{
                        this.$message({
                            type:"error",
                            message:data.msg
                        });
                    }

                })
            },
            handleSizeChange(val) {
                console.log(`每页 ${val} 条`);
                this.pageSize=val;
                this.initData()
            },
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`);
                this.pageNum=val;
                this.initData()
            },
            initData(){
                axios.get(`/role`,{params:{
                        pageNum: this.pageNum,
                        pageSize: this.pageSize
                    }}).then(resp=>{
                        let data=resp.data;
                      this.roles=data.result;
                      this.total=data.count
                })
            }
        },
        created(){
            this.initData();
        }
    })
</script>
</body>
</html>